package com.jin.lazytool.componment;

import javafx.scene.control.TextField;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NumberField extends TextField {

    Pattern pattern = Pattern.compile("[0-9]*$");
    private Long min = null;
    private Long max = null;

    public void setMin(Integer min){
        this.min = Long.valueOf(min);
    }
    public void setMax(Integer max){
        this.max = Long.valueOf(max);
    }

    public void setMin(Long min){
        this.min = min;
    }
    public void setMax(Long max){
        this.max = max;
    }

    public NumberField(){
        super("");
        addListener();
    }
    public NumberField(Integer value){
        super(String.valueOf(value));
        addListener();
    }
    public NumberField(Long value){
        super(String.valueOf(value));
        addListener();
    }
    private void addListener(){
        this.textProperty().addListener((observable, oldValue, newValue) -> {
            if("".equals(newValue)){
                return;
            }
            Matcher isNum = pattern.matcher(newValue);
            if(!isNum.matches()){
                setText(oldValue);
            }
            long val = Long.parseLong(getText());
            if(min != null && val < min){
                setText(String.valueOf(min));
            }else if(max != null && val > max){
                setText(String.valueOf(max));
            }
        });
    }

    public Integer getValue(){
        String text = getText();
        if(text == null || "".equals(text)){
            return null;
        }
        return Integer.parseInt(getText());
    }
    public void setValue(Integer value){
        if(value != null){
            setText(value.toString());
        }
    }
    public void setValue(Long value){
        if(value != null){
            setText(value.toString());
        }
    }
    public Integer getNullDefaultValue(){
        String text = getText();
        if(text == null || "".equals(text)){
            return 0;
        }
        return Integer.parseInt(getText());
    }

}

